#include "OnlineUsers.h"

#include "util/definitions.h"
#include "util/util.h"
#include "util/Log.h"

#include "lib/LockFile.h"

#include <stdio.h>
#include <iostream>



OnlineUsers::OnlineUsers(int myID) {
	myUserID=myID;
}


OnlineUsers::OnlineUsers() {
	myUserID=getpid();
}

OnlineUsers::~OnlineUsers() {

}

void OnlineUsers::getOnlineUsers(std::list<int> & users)
{
	LockFile usersFile(getPathOnlineUsers().c_str());

	int read = 0, userID = 0;

	/* go through the online-users file and add users to the list */

	usersFile.tomarLock(lock_lectura);

	usersFile.seek(0);

	do
	{
		read = usersFile.leer((char*)&userID , sizeof(userID));

		if ( userID > 0)
		{
			users.push_back(userID);
		}

		userID = 0;

	} while (read > 0);

	usersFile.liberarLock();

}

bool OnlineUsers::isUserOnline(int userID, bool deleteUser)
{
	int id = 0;

	if ( userID > 0)
	{
		LockFile usersFile( getPathOnlineUsers().c_str());

		int read = 0, bytes = 0;

		/* search for the user inside the online-users file */

		usersFile.tomarLock(lock_lectura);

		usersFile.seek(0);

		do
		{
			id = 0;
			read = usersFile.leer((char*)&id , sizeof(id));
			bytes += read;
		} while (read > 0 && id != userID);

		if ( (id == userID) && deleteUser )
		{
			id = 0;
			usersFile.seek( bytes - sizeof(id));
			usersFile.tomarLock(lock_escritura);
			usersFile.escribir((char*)&id, sizeof(id));
			id = userID;
		}

		usersFile.liberarLock();
	}

	return (id == userID);

}

void OnlineUsers::logIn()
{
	if ( myUserID > 0)
	{
		/* check if the user is online */
		if ( ! isUserOnline(myUserID) )
		{
			Log::getInstance().log(myUserID, "Conectado");
			/* add user to the online users list */

			LockFile usersFile(getPathOnlineUsers().c_str());

			usersFile.tomarLock(lock_escritura);
			usersFile.append((char*)&myUserID , sizeof(myUserID));
			usersFile.liberarLock();

			Log::getInstance().log(myUserID, "Usuario conectado");
		}
		else
			//TODO
			std::clog<<"El usuario "<<myUserID<<" ya estaba conectado"<<std::endl;
	}

}

void OnlineUsers::logOut()
{
	/* remove from logged in users */
	if ( isUserOnline(myUserID,true) )
	{
		/* remove file with listed shared files of that user */

		remove(getPathSharedFiles(myUserID).c_str());
		remove(getPathSharedFilesBitmap(myUserID).c_str());
		remove(getSemaphoreKeyFile(myUserID).c_str());

		Log::getInstance().log(myUserID, "Usuario desconectado");
	}
}

void OnlineUsers::removeOnlineUsersDatabase()
{
	remove(getPathOnlineUsers().c_str());
}



